import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/values/index.dart';
import '../../../common/widgets/index.dart';
import 'index.dart';

class ProcessWebviewPage extends GetView<ProcessWebviewController> {
  const ProcessWebviewPage({Key? key, required this.tag}) : super(key: key);
  @override
  final String? tag;

  static Future<dynamic> openJob(String job) async {
    if (job.isEmpty) {
      return null;
    }
    try {
      final result = await ProcessSurfaceService.to.getWorkByJob(job);
      final count = (result?.workCompletedList?.length ?? 0) +
          (result?.workList?.length ?? 0);
      if (result == null || count < 1) {
        Loading.showError('process_job_not_found'.tr);
        return null;
      }
      List<Work> works = [];
      if (result.workList?.isNotEmpty == true) {
        works.addAll(result.workList!);
      }
      if (result.workCompletedList?.isNotEmpty == true) {
        works.addAll(result.workCompletedList!);
      }
      if (works.isEmpty) {
        Loading.showError('process_job_not_found'.tr);
        return null;
      }
      final context = Get.context;
      if (context == null) {
        return null;
      }
      if (works.length == 1) {
        ProcessWebviewPage.open(works[0].id!, title: works[0].title ?? '');
      } else {
        // ignore: use_build_context_synchronously
        O2UI.showBottomSheetWithCancel(
            context,
            works.map((w) {
              return ListTile(
                onTap: () {
                  Navigator.pop(context);
                  ProcessWebviewPage.open(w.id!, title: w.title ?? '');
                },
                title: Align(
                  alignment: Alignment.center,
                  child: Text('${w.title} 【${w.processName}】',
                      style: Theme.of(context).textTheme.bodyMedium),
                ),
              );
            }).toList());
      }
      return true;
    } catch (e) {
      OLogger.e('错误', e);
      Loading.showError('process_job_not_found'.tr);
      return null;
    }
  }

  static Future<void> open(String workOrWorkCompletedId,
      {String title = '', bool isCloseCurrentPage = false}) async {
    Get.lazyPut<ProcessWebviewController>(() => ProcessWebviewController(),
        tag: workOrWorkCompletedId);
    if (isCloseCurrentPage) {
      await Get.off(ProcessWebviewPage(tag: workOrWorkCompletedId),
          arguments: {
            "workOrWorkCompletedId": workOrWorkCompletedId,
            "title": title
          },
          preventDuplicates: false);
    } else {
      await Get.to(ProcessWebviewPage(tag: workOrWorkCompletedId),
          arguments: {
            "workOrWorkCompletedId": workOrWorkCompletedId,
            "title": title
          },
          preventDuplicates: false); // preventDuplicates 可打开多个
    }
  }

  static Future<void> openDraft(ProcessDraftWorkData draft,
      {bool isCloseCurrentPage = false}) async {
    Get.lazyPut<ProcessWebviewController>(() => ProcessWebviewController(),
        tag: draft.id!);
    if (isCloseCurrentPage) {
      await Get.off(ProcessWebviewPage(tag: draft.id!),
          arguments: {"draft": draft});
    } else {
      await Get.to(ProcessWebviewPage(tag: draft.id!),
          arguments: {"draft": draft});
    }
  }

  @override
  Widget build(BuildContext context) {
    OLogger.d('流程表单 build 。。。。。。。。。。。');
    return GetBuilder<ProcessWebviewController>(
      tag: tag,
      builder: (_) {
        OLogger.d('流程表单 GetBuilder 。。。。。。。。。。。');
        return WillPopScope(
            // 拦截物理返回
            onWillPop: () {
              controller.tapBackBtn();
              return Future.value(false);
            },
            child: Scaffold(
              appBar: AppBar(
                  leading: IconButton(
                    icon: const Icon(Icons.arrow_back),
                    onPressed: () => {controller.tapBackBtn()},
                  ),
                  title: Obx(() => Text(controller.state.title)),
                  actions: [
                    O2UI.webviewPopupMenu(() => controller.copyLink())
                  ]),
              body: SafeArea(
                child: Obx(() => controller.state.url.isEmpty
                    ? const Center(child: CircularProgressIndicator())
                    : _buildWebView()),
              ),
            ));
      },
    );
  }

  // 主视图
  Widget _buildWebView() {
    OLogger.d('流程表单 _buildWebView 。。。。。。。。。。。');
    return InAppWebView(
        key: GlobalKey(),
        initialUrlRequest: URLRequest(url: Uri.parse(controller.state.url)),
        initialOptions: InAppWebViewGroupOptions(
            crossPlatform: InAppWebViewOptions(
                useShouldOverrideUrlLoading: true,
                useOnDownloadStart: true,
                javaScriptCanOpenWindowsAutomatically: true,
                mediaPlaybackRequiresUserGesture: false,
                applicationNameForUserAgent: O2.webviewUserAgent),
            android: AndroidInAppWebViewOptions(
              useHybridComposition: true,
              supportMultipleWindows: true,
            ),
            ios: IOSInAppWebViewOptions(
              allowsInlineMediaPlayback: true,
            )),
        onWebViewCreated: (c) {
          OLogger.d('流程表单 onWebViewCreated 。。。。。。。。。。。');
          controller.setupWebviewJsHandler(c);
        },
        // onCreateWindow: (c, createWindowRequest) async {
        //   OLogger.d("创建新窗口，，，，${createWindowRequest.request.url}");
        // },
        shouldOverrideUrlLoading: (c, navigationAction) async {
          var uri = navigationAction.request.url!;
          OLogger.d("流程表单  shouldOverrideUrlLoading uri: $uri");
          return NavigationActionPolicy.ALLOW;
        },
        onProgressChanged: (c, p) {
          controller.progressChanged(c, p);
        },
        // h5下载文件
        onDownloadStartRequest: (c, request) async {
          controller.webviewHelper.onFileDownloadStart(request);
        },
        onTitleChanged: ((c, title) {
          OLogger.d('修改网页标题： $title');
          if (title != null && title.isNotEmpty) {
            controller.state.title = title;
          }
        }),
        onConsoleMessage: (c, consoleMessage) {
          OLogger.i("console: $consoleMessage");
        });
  }
}
